<script lang="ts" setup>
import { reactive, ref, watch } from "vue"
import {
  type FormInstance,
  type FormRules,
  ElMessage,
  ElMessageBox,
  type UploadInstance,
  type UploadUserFile,
  type UploadRequestOptions
} from "element-plus"
import { Search, Refresh, CirclePlus, Delete, RefreshRight, Upload } from "@element-plus/icons-vue"
import { usePagination } from "@/hooks/usePagination"
import {
  SchoolTypeList,
  getSchoolList,
  postInsertSchool,
  putUpdateSchool,
  deleteSchool,
  importSchool
} from "@/api/user"
import type { InsertSchoolParam, School, UpdateSchoolParam } from "@/api/user"
import { formatDate } from "@/utils"
import area from "@/assets/area.json"

defineOptions({
  name: "School"
})

const loading = ref<boolean>(false)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()

//#region 增
const dialogVisible = ref<boolean>(false)
const formRef = ref<FormInstance | null>(null)
const formData = reactive({
  sid: "",
  name: "",
  type: 0,
  area: [],
  remark: ""
})
const formRules: FormRules = reactive({
  name: [{ required: true, trigger: "blur", message: "请输入学校名称" }],
  type: [{ required: true, trigger: "blur", message: "请选择学校类型" }],
  sId: [{ required: true, trigger: "blur", message: "请输入学校编号" }],
  area: [{ required: true, trigger: "blur", message: "请选择学校所在省市" }]
})
const handleCreate = () => {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      if (currentUpdateId.value === undefined) {
        const data: InsertSchoolParam = {
          sid: formData.sid,
          name: formData.name,
          type: formData.type,
          province: formData.area[0] ?? "",
          city: formData.area[1] ?? "",
          remark: formData.remark
        }
        postInsertSchool(data).then(() => {
          ElMessage.success("新增成功")
          dialogVisible.value = false
          getTableData()
        })
      } else {
        const data: UpdateSchoolParam = {
          sid: currentUpdateId.value,
          name: formData.name,
          type: formData.type,
          province: formData.area[0] ?? "",
          city: formData.area[1] ?? "",
          remark: formData.remark
        }
        putUpdateSchool(data).then(() => {
          ElMessage.success("修改成功")
          dialogVisible.value = false
          getTableData()
        })
      }
    } else {
      return false
    }
  })
}
const resetForm = () => {
  currentUpdateId.value = undefined
}
//#endregion
// 新增学校信息
const handlerInsertSchool = () => {
  formData.sid = ""
  formData.name = ""
  formData.type = 0
  formData.area = []
  formData.remark = ""
  dialogVisible.value = true
}
//#region 删
const handleDelete = (row: School) => {
  ElMessageBox.confirm(`正在删除学校：${row.name}，确认删除？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deleteSchool([row.sid]).then(() => {
      ElMessage.success("删除成功")
      getTableData()
    })
  })
}
//#endregion

//#region 改
const currentUpdateId = ref<undefined | string>(undefined)
const handleUpdate = (row: School) => {
  currentUpdateId.value = row.sid
  formData.sid = row.sid
  formData.name = row.name
  formData.type = row.type
  formData.area = [row.province, row.city]
  formData.remark = row.remark
  dialogVisible.value = true
}

//#region 查
const tableData = ref<School[]>([])

const tableSelects = ref<School[]>([])
// 表格选中更改事件
const tableSelectionChange = (rows: School[]) => {
  tableSelects.value = rows
}
const handlerSchoolBatchDel = () => {
  tableSelects.value.length > 0 &&
    ElMessageBox.confirm(
      `正在删除学校：${tableSelects.value.map((item) => item.name).join("、")}，确认删除？`,
      "提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    ).then(() => {
      deleteSchool(tableSelects.value.map((item) => item.sid)).then(() => {
        ElMessage.success("删除成功")
        getTableData()
      })
    })
}
const searchFormRef = ref<FormInstance | null>(null)
const searchData = reactive({
  name: "",
  area: []
})
const areaProps = reactive({
  value: "ext_name",
  label: "ext_name",
  children: "childs",
  checkStrictly: true
})
const getTableData = () => {
  loading.value = true
  getSchoolList({
    pageSize: paginationData.pageSize,
    pageNum: paginationData.currentPage,
    name: searchData.name,
    province: searchData.area[0] || "",
    city: searchData.area[1] || ""
  })
    .then((res) => {
      paginationData.total = res.data.total
      tableData.value = res.data.records
    })
    .catch(() => {
      tableData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}
const handleSearch = () => {
  if (paginationData.currentPage === 1) {
    getTableData()
  }
  paginationData.currentPage = 1
}
const resetSearch = () => {
  searchData.name = ""
  searchData.area = []
  searchFormRef.value?.resetFields()
  if (paginationData.currentPage === 1) {
    getTableData()
  }
  paginationData.currentPage = 1
}
const handleRefresh = () => {
  getTableData()
}
// 定义响应式数据
const uploadDialogVisible = ref(false)
const fileList = ref<UploadUserFile[]>([])

// 打开弹窗
const openDialog = () => {
  uploadDialogVisible.value = true
}

const uploadExcel = ref<UploadInstance | null>(null)
// 上传文件
const uploadFile = async () => {
  if (uploadExcel.value) {
    uploadExcel.value.submit()
  }
}
const uploadExcelFile = async (options: UploadRequestOptions) => {
  const formData = new FormData()
  formData.set("file", options.file)
  const isOk = await importSchool(formData)
  if (isOk) {
    ElMessage.success("导入成功")
    // 关闭弹窗
    uploadDialogVisible.value = false
    // 刷新表格数据
    getTableData()
  }
}

//#endregion

/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })
</script>

<template>
  <div class="app-container">
    <el-card v-loading="loading" shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="username" label="学校名称">
          <el-input v-model="searchData.name" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="地区">
          <el-cascader
            v-model="searchData.area"
            placeholder="选择省/市"
            clearable
            :options="area"
            :props="areaProps"
            filterable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card v-loading="loading" shadow="never">
      <div class="toolbar-wrapper">
        <div>
          <el-button type="primary" :icon="CirclePlus" @click="handlerInsertSchool">新增学校</el-button>
          <el-button type="danger" :icon="Delete" @click="handlerSchoolBatchDel">批量删除</el-button>
        </div>
        <div>
          <!--          <el-tooltip content="下载">-->
          <!--            <el-button type="primary" :icon="Download" circle />-->
          <!--          </el-tooltip>-->
          <el-tooltip content="刷新表格">
            <el-button type="primary" :icon="RefreshRight" circle @click="handleRefresh" />
          </el-tooltip>
          <el-tooltip content="导入学校信息">
            <el-button type="primary" :icon="Upload" circle @click="openDialog" />
          </el-tooltip>
        </div>
      </div>
      <div class="table-wrapper">
        <el-table :data="tableData" @selection-change="tableSelectionChange">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column prop="sid" label="学校编号" width="110px" align="left" />
          <el-table-column prop="name" label="学校名称" align="left" />
          <el-table-column prop="province" label="所在省" align="center" />
          <el-table-column prop="city" label="所在市" align="center" />
          <el-table-column prop="createTime" label="导入时间" align="center">
            <template #default="scope">
              {{ formatDate(scope.row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="updateTime" label="最后修改时间" align="center">
            <template #default="scope">
              {{ formatDate(scope.row.updateTime) }}
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="150" align="center">
            <template #default="scope">
              <el-button type="primary" text bg size="small" @click="handleUpdate(scope.row)">修改</el-button>
              <el-button type="danger" text bg size="small" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 新增/修改 -->
    <el-dialog
      v-model="dialogVisible"
      :title="currentUpdateId === undefined ? '新增学校' : '修改学校信息'"
      @close="resetForm"
      width="500px"
    >
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" label-position="left">
        <el-form-item prop="sid" label="学校代码">
          <el-input v-model="formData.sid" placeholder="请输入学校代码" />
        </el-form-item>
        <el-form-item prop="name" label="学校名称">
          <el-input v-model="formData.name" placeholder="请输入学校名称" />
        </el-form-item>
        <el-form-item prop="type" label="学校类型">
          <el-select v-model="formData.type">
            <template v-for="(item, index) in SchoolTypeList" :key="index">
              <el-option :label="item" :value="index" />
            </template>
          </el-select>
        </el-form-item>
        <el-form-item prop="area" label="地区">
          <el-cascader
            v-model="formData.area"
            placeholder="选择省/市"
            clearable
            :options="area"
            :props="{ ...areaProps, checkStrictly: false }"
            filterable
          />
        </el-form-item>
        <el-form-item prop="remark" label="备注">
          <el-input v-model="formData.remark" type="textarea" :max="5" placeholder="输入学校备注信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreate">确认</el-button>
      </template>
    </el-dialog>
    <el-dialog v-model="uploadDialogVisible" title="上传文件">
      <el-upload
        ref="uploadExcel"
        class="upload-dragger"
        v-model:file-list="fileList"
        drag
        :auto-upload="false"
        name="file"
        :http-request="uploadExcelFile"
      >
        <i class="el-icon-upload" />
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      </el-upload>
      <el-button type="primary" @click="uploadFile">上传</el-button>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;

  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
</style>
